package com.googlecode.dgwt.client.dijit.base.widget;

import java.util.AbstractSet;
import java.util.Iterator;

import com.googlecode.dgwt.client.dijit.View;
import com.googlecode.dgwt.client.dijit.Widget;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class ViewList extends AbstractSet<View> {

    private Widget widget;
    
    public ViewList(Widget widget){
        this.widget = widget;
    }
    
    @Override
    public Iterator<View> iterator() {
        return widget.getEngine().new HandlerIterator<View>() {

            @Override
            protected boolean isInstance(UIHandler handler) {
                return handler instanceof ViewHandler;
            }

            @Override
            protected View getTarget(UIHandler handler) {
                return ((ViewHandler)handler).getView();
            }
            
        };
    }

    @Override
    public boolean add(View view) {
        if (view != null
                && view.getWidget() != widget
                && !contains(view)){
            widget.getEngine().addHandler(new ViewHandler(view));
        }
        return false;
    }

    @Override
    public int size() {
        int size = 0;
        for (Iterator<View> iterator = iterator(); iterator.hasNext();){
            size++;
        }
        return size;
    }

    public View findView(String name){
        if (name == null){
            for (View view : this){
                if (view.getName() == null){
                    return view;
                }
            }
        } else {
            for (View view : this){
                if (name.equals(view.getName())){
                    return view;
                }
            }
        }
        return null;
    }

    public View findView(Widget widget){
        if (widget != null){
            for (View view : this){
                if (view.getWidget().equals(widget)){
                    return view;
                }
            }
        }
        return null;
    }

}
